<?php
namespace my;
use my\Front;
use org\Upload;
use org\Image;

class Up{
    /**
     * 上传单个图片
     * @param string $dir          目录
     * @param string $name          上传字段名称
     * @param string $is_thumb      是否生成缩略图
     * @param unknown $con_thumb    缩略图大小配置
     * @return 返回图片路径
     */
    public static function upPic($dir='', $name='file', $is_thumb = true, $con_thumb = ['small'=>[100,100], 'middle'=>[300,300]]){
        if( !current($_FILES) )
            return com_error('上传图片字段不存在!');

        //上传图片
        $dir = $dir ? $dir : "default";
        $base   = c('a.uploads').$dir."/";
        com_mkdir($base);
        $config = [
            'maxSize'      => 20971520,
            'exts'      => ['jpg', 'gif', 'png', 'jpeg','ico'],
            'mimes'     => ['image/png', 'image/jpg','image/gif', 'image/jpeg','image/x-icon'],
            'rootPath'  => $base,
            'driver'    => 'Local',
            'savePath'  => date('Y-m').'/',
            'subName'   => ['date', 'd'],
        ];
        $up   = new Upload( $config );
        $info = $up->uploadOne( current($_FILES) );
        if($info==false)
            return com_error( $up->getError() );

        //返回图片路径
        $path = $base.$info['savepath'].$info['savename'];
        if( $is_thumb && $con_thumb){#生成缩略图
              $img = new Image();
              foreach($con_thumb as $k => $v){
                  $gd = $img->init('Gd', $path);
                  $gd->thumb($v[0], $v[1]);
                  $gd->save($base.$info['savepath'].$k.'_'.$info['savename']);
              }
        }
        return $path;
    }
    /**
     * 上传文件
     * @param string $dir  上传到目录
     * @param string $name  上传文件字段
     * @param unknown $exts 允许文件的后缀名
     */
    public static function upFile($dir='rsa', $name='pic', $exts = []){
        if( !isset($_FILES[$name]) )
            return com_error([$name=>'上传文件字段不存在!']);

        //上传图片
        $base   = c('a.uploads').com_module()."/";
        com_mkdir($base);
        $config = [
            'exts'      => $exts,
            'rootPath'  => $base,
            'driver'    => 'Local',
            'savePath'  => $dir.'/'.date('Y-m').'/',
            'subName'   => ['date', 'd'],
        ];

        $up   = new Upload( $config );
        $info = $up->uploadOne( $_FILES[$name] );
        if($info==false)
            return com_error( [$name=>$up->getError()] );
        //返回路径
        return $base.$info['savepath'].$info['savename'];
    }
}
